package com.example.firstjavamqtt.config;


import com.example.firstjavamqtt.model.base.User;
import com.example.firstjavamqtt.service.base.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //TODO 增加权限部分 限定用户和管理员的权限
    /**
     * 认证 ，用户名密码校验
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        User user = userService.getByUsername(username);
        if (user == null) {
            throw new UnknownAccountException(); // 账号不存在
        }
        String salt = user.getSalt();
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,
                user.getPassword(),
                ByteSource.Util.bytes(salt),
                getName());

        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取主身份信息
        String principal = (String) principalCollection.getPrimaryPrincipal();
        // 根据主身份信息获取用户
        User user = userService.getByUsername(principal);
        String role = user.getRole();
        System.out.println(role);
        if (role.equals("超级管理员")) {
            System.out.println("Here");
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRole(role);
            simpleAuthorizationInfo.addStringPermission("log:*:*");
            return simpleAuthorizationInfo;
        }
        return null;
    }
}
